package com.common.android.ui.LocalAlbum;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Observer;
import java.util.concurrent.PriorityBlockingQueue;

public class LocalImageController {	
	private static LocalImageController sInstance = new LocalImageController();
	private HashSet<Observer> mObservers;
	private PriorityBlockingQueue<SortedMediaFiles> mPbq;	
	
	private LocalImageController() {		
		mObservers = new HashSet<Observer>();

		mPbq = new PriorityBlockingQueue<SortedMediaFiles>(11, new Comparator<SortedMediaFiles>() {
					@Override
					public int compare(SortedMediaFiles lhs, SortedMediaFiles rhs) {
						return lhs.mDirInfo.lastModifiedCmp(rhs.mDirInfo);
					}
				});
	}
	
	public static LocalImageController getInstance() {
//		if(null == sInstance){
//			sInstance =  new LocalImageController();
//		}
		
		return sInstance;
	}	
	
	public void addObserver(Observer o) {
		mObservers.add(o);
	}

	public void delObserver(Observer o) {
		mObservers.remove(o);
	}

	public void notifyObservers() {
		for (Observer o : mObservers) {
			o.update(null, null);
		}
	}
	
	public PriorityBlockingQueue<SortedMediaFiles> getPbq(){
		return mPbq;
	}

	public void addMediaFile(SortedMediaFiles smf) {
		mPbq.add(smf);
	}

	public ArrayList<SortedMediaFiles> getMediaFiles() {
		ArrayList<SortedMediaFiles> list = new ArrayList<SortedMediaFiles>();

//		int iDCIMPos = -1;	//相册目录索引
		SortedMediaFiles smf = mPbq.poll();
		while (smf != null) {
//			if(smf.isInCameraPath()){
//				iDCIMPos = list.size();
//			}
			list.add(smf);
			smf = mPbq.poll();
		}

		for (SortedMediaFiles temp : list) {
			mPbq.add(temp);
		}

		//将相册目录移到表头
//		if(-1 != iDCIMPos){
//			smf = list.get(iDCIMPos);
//			list.remove(iDCIMPos);
//			list.add(0, smf);
//		}
		
		return list;
	}

	/**
	 * 获取图片文件数据，并且相册目录在最前面
	 * 
	 * <br>
	 * Created 2014-5-12 下午9:09:13
	 * 
	 * @return 文件数据列表
	 * @author : HuangYK
	 */
	public ArrayList<SortedMediaFiles> getMediaFilesByCameraFirst() {
		ArrayList<SortedMediaFiles> list = new ArrayList<SortedMediaFiles>();

		int iDCIMPos = -1; // 相册目录索引
		SortedMediaFiles smf = mPbq.poll();
		while (smf != null) {
			if (smf.isTheCameraPath()) {
				iDCIMPos = list.size();
			}
			list.add(smf);
			smf = mPbq.poll();
		}

		for (SortedMediaFiles temp : list) {
			mPbq.add(temp);
		}

		// 将相册目录移到表头
		if (-1 != iDCIMPos) {
			smf = list.get(iDCIMPos);
			list.remove(iDCIMPos);
			list.add(0, smf);
		}

		return list;
	}

	public void clearLocalMedia() {
		mPbq.clear();
	}
}
